import request from '@/router/axios'
import { eggUrl } from '@/config/env'
import store from "@/store";
import {
    Message
} from 'element-ui';

export const http = async (url, source, page, method = "POST") => {
    let adminId = store.state.user.userInfo.id
    let param = {
        adminId
    }
    if (page) {
        param.pageNum = page.currentPage
        param.pageSize = page.pageSize
    }
    if (source) {
        param.startTime = source.startTime
        param.endTime = source.endTime
        delete source["startTime"]
        delete source["endTime"]
    }
    if (!source) {
        source = {}
    }
    source.updateAdminId = adminId
    if (method.toLocaleUpperCase() === "GET") {
        param = source
    } else {
        param.source = source
    }
    if (!url.startsWith('http')) {
        url = eggUrl + url;
    }
    let response = await request({
        url: url,
        method: method,
        params: method == "GET" ? param : null,
        data: method == "GET" ? null : param
    })
    // 处理返回值结果
    let data = response.data;
    if (data.code % 100 === 1) {
        if (url == "/member/editRedCentInfo") {
            if (data.message != "") {
                Message.error(data.message)
            }
        }
        return Result.success(data)
    }
    data.message && Message.error(data.message);
    return null;
}

class Result {
    constructor(data, page) {
        this.data = data
        this.page = page
    }

    static success(result) {
        let page = {}
        let data
        let code
        if (result.total) {
            // 表示是分页查询
            page.total = result.total
            page.pageSize = result.size;
            page.currentPage = result.current;
            data = result.rows
        } else {
            // Message.success("操作成功");
            data = result.source
        }
        code = result.code
        if (!data) {
            data = []
        }
        return new Result(data, page)
    }
}



